import React from 'react'
import Form from './Form'
import List from './List'
import Dialog from './Dialog'

class Todolist extends React.Component {

  constructor() {
    super();
    this.state = {
      showAdd: false,
      showUpdate:false,
      current:{
        id:'',
        name:''
      },
      keyword: '',
      datalist: [{
        id: 1,
        name: "太原"
      },
      {
        id: 2,
        name: "北京"
      }
      ]
    }
  }

  handerSearch(keyword) {
    console.log(keyword);
    this.setState({
      keyword
    })
  }

  addSubmit(txt) {
    // this.state.datalist.push({
    //   id: parseInt(Math.random() * 10000),
    //   name: txt
    // })
    this.setState({
      datalist: this.state.datalist.concat([{
        id: parseInt(Math.random() * 10000),
        name: txt
      }]),
      showAdd: false
    })
  }

  handleDel = (id) => {
    let idx = -1;
    this.state.datalist.find((item, index) => {
      idx = index;
      return item.id === id;
    })
    this.state.datalist.splice(idx,1)
    this.setState({})
  }

  updateSubmit(txt){
    let idx = -1;
    this.state.datalist.find((item, index) => {
      idx = index;
      return item.id === this.state.current.id;
    })
    // this.state.datalist[idx].name = txt;
    let tmp = JSON.parse(JSON.stringify(this.state.datalist))
    tmp[idx].name = txt;
    this.setState({
      datalist:tmp,
      showUpdate:false
    })
  }

  render() {
    let tmp = this.state.datalist.filter((item) => {
      return item.name.indexOf(this.state.keyword) > -1
    })

    let add = (
      <Dialog>
        <input type="text" ref="txt" />
        <button onClick={() => this.addSubmit(this.refs.txt.value)}>添加</button>
        <button onClick={() => this.setState({ showAdd: false })}>取消</button>
      </Dialog>
    )


    let edit = (
      <Dialog>
        <input type="text" ref="txt" defaultValue={this.state.current.name} />
        <button onClick={() => this.updateSubmit(this.refs.txt.value)}>更新</button>
        <button onClick={() => this.setState({ showUpdate: false })}>取消</button>
      </Dialog>
    )

    return (
      <>
        <Form
          search={(keyword) => this.handerSearch(keyword)}
          add={() => this.setState({ showAdd: true })}
        ></Form>
        <List list={tmp}
          del={this.handleDel}
          edit={(item)=>{
            this.setState({
              showUpdate:true,
              current:{...item}
            })
          }}
        ></List>
        {
          this.state.showAdd ? add : ''
        }
        {
          this.state.showUpdate? edit :''
        }

      </>
    )
  }
}

export default Todolist;